<template>
  <div class="component-examples">
    <a-typography-title :level="1">Ant Design Vue 高级功能集成示例</a-typography-title>
    
    <!-- Pro Components 示例 -->
    <section class="example-section">
      <a-typography-title :level="2">Pro Components</a-typography-title>
      
      <!-- ProTable 示例 -->
      <div class="example-item">
        <a-typography-title :level="3">ProTable 高级表格</a-typography-title>
        <ProTable
          :columns="tableColumns"
          :data-source="tableData"
          :loading="tableLoading"
          :show-toolbar="true"
          :show-search="true"
          row-key="id"
          @refresh="handleTableRefresh"
          @search="handleTableSearch"
        >
          <template #toolbar-right>
            <a-button type="primary" @click="handleAddEntity">
              <plus-outlined />
              新增生命体
            </a-button>
          </template>
          
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'status'">
              <a-tag :color="getStatusColor(record.status)">
                {{ getStatusLabel(record.status) }}
              </a-tag>
            </template>
            <template v-if="column.key === 'actions'">
              <a-space>
                <a-button type="link" size="small" @click="handleView(record)">
                  查看
                </a-button>
                <a-button type="link" size="small" @click="handleEdit(record)">
                  编辑
                </a-button>
              </a-space>
            </template>
          </template>
        </ProTable>
      </div>
      
      <!-- ProForm 示例 -->
      <div class="example-item">
        <a-typography-title :level="3">ProForm 高级表单</a-typography-title>
        <ProForm
          :fields="formFields"
          :initial-values="formInitialValues"
          :submitting="formSubmitting"
          @submit="handleFormSubmit"
          @reset="handleFormReset"
        />
      </div>
      
      <!-- ProCard 示例 -->
      <div class="example-item">
        <a-typography-title :level="3">ProCard 高级卡片</a-typography-title>
        <a-row :gutter="16">
          <a-col :span="8">
            <ProCard
              title="统计卡片"
              :statistic="{
                title: '活跃生命体',
                value: 1234,
                suffix: '个',
                description: '较昨日增长 12%'
              }"
              :show-refresh="true"
              @refresh="handleCardRefresh"
            />
          </a-col>
          <a-col :span="8">
            <ProCard
              title="图表卡片"
              :chart="true"
              chart-height="200px"
              :show-fullscreen="true"
            >
              <template #chart>
                <div style="height: 200px; display: flex; align-items: center; justify-content: center; background: #f5f5f5; border-radius: 4px;">
                  <line-chart-outlined style="font-size: 48px; color: #d9d9d9" />
                </div>
              </template>
            </ProCard>
          </a-col>
          <a-col :span="8">
            <ProCard
              title="操作卡片"
              :actions="[
                { key: 'action1', text: '操作1', type: 'primary', onClick: () => console.log('操作1') },
                { key: 'action2', text: '操作2', onClick: () => console.log('操作2') }
              ]"
            >
              <p>这是一个带操作按钮的卡片示例。</p>
            </ProCard>
          </a-col>
        </a-row>
      </div>
    </section>
    
    <!-- Loading Components 示例 -->
    <section class="example-section">
      <a-typography-title :level="2">Loading Components</a-typography-title>
      
      <div class="example-item">
        <a-typography-title :level="3">全局加载状态</a-typography-title>
        <a-space>
          <a-button @click="showGlobalLoading">显示全局加载</a-button>
          <a-button @click="showProgressLoading">显示进度加载</a-button>
          <a-button @click="hideGlobalLoading">隐藏加载</a-button>
        </a-space>
      </div>
      
      <div class="example-item">
        <a-typography-title :level="3">骨架屏</a-typography-title>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-card title="列表骨架屏">
              <SkeletonLoader
                preset="list"
                :active="skeletonActive"
                :rows="3"
              />
              <a-button @click="skeletonActive = !skeletonActive" style="margin-top: 16px">
                {{ skeletonActive ? '隐藏' : '显示' }}骨架屏
              </a-button>
            </a-card>
          </a-col>
          <a-col :span="12">
            <a-card title="表格骨架屏">
              <SkeletonLoader
                preset="table"
                :active="skeletonActive"
                :rows="4"
                :columns="3"
              />
            </a-card>
          </a-col>
        </a-row>
      </div>
    </section>
    
    <!-- Business Components 示例 -->
    <section class="example-section">
      <a-typography-title :level="2">Business Components</a-typography-title>
      
      <div class="example-item">
        <a-typography-title :level="3">生命体卡片</a-typography-title>
        <a-row :gutter="16">
          <a-col :span="8" v-for="entity in sampleEntities" :key="entity.id">
            <LifeEntityCard
              :entity="entity"
              @view="handleEntityView"
              @edit="handleEntityEdit"
              @delete="handleEntityDelete"
            />
          </a-col>
        </a-row>
      </div>
      
      <div class="example-item">
        <a-typography-title :level="3">网络状态卡片</a-typography-title>
        <NetworkStatusCard
          :network-health="networkHealth"
          :network-stats="networkStats"
          :network-metrics="networkMetrics"
          :alerts="networkAlerts"
          @refresh="handleNetworkRefresh"
        />
      </div>
    </section>
    
    <!-- 无障碍访问示例 -->
    <section class="example-section">
      <a-typography-title :level="2">无障碍访问功能</a-typography-title>
      
      <div class="example-item">
        <a-typography-title :level="3">无障碍设置</a-typography-title>
        <a-form layout="vertical">
          <a-form-item label="键盘导航">
            <a-switch 
              v-model:checked="accessibilityConfig.keyboardNavigation"
              @change="updateAccessibilityConfig"
            />
          </a-form-item>
          <a-form-item label="屏幕阅读器支持">
            <a-switch 
              v-model:checked="accessibilityConfig.screenReader"
              @change="updateAccessibilityConfig"
            />
          </a-form-item>
          <a-form-item label="高对比度模式">
            <a-switch 
              v-model:checked="accessibilityConfig.highContrast"
              @change="updateAccessibilityConfig"
            />
          </a-form-item>
          <a-form-item label="大字体模式">
            <a-switch 
              v-model:checked="accessibilityConfig.largeFont"
              @change="updateAccessibilityConfig"
            />
          </a-form-item>
          <a-form-item label="减少动画">
            <a-switch 
              v-model:checked="accessibilityConfig.reducedMotion"
              @change="updateAccessibilityConfig"
            />
          </a-form-item>
        </a-form>
        
        <a-space style="margin-top: 16px">
          <a-button @click="testScreenReader">测试屏幕阅读器</a-button>
          <a-button @click="testKeyboardNavigation">测试键盘导航</a-button>
        </a-space>
      </div>
    </section>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { 
  ProTable, ProForm, ProCard, 
  SkeletonLoader, LifeEntityCard, NetworkStatusCard,
  useGlobalLoading, useAccessibility, useScreenReader
} from '@/components'
import { PlusOutlined, LineChartOutlined } from '@ant-design/icons-vue'

// Global Loading
const { showLoading, hideLoading, setProgress } = useGlobalLoading()
const { config: accessibilityConfig, updateConfig } = useAccessibility()
const { announce } = useScreenReader()

// Table 示例数据
const tableLoading = ref(false)
const tableColumns = [
  { title: '名称', dataIndex: 'name', key: 'name' },
  { title: '类型', dataIndex: 'type', key: 'type' },
  { title: '状态', dataIndex: 'status', key: 'status' },
  { title: '创建时间', dataIndex: 'createdAt', key: 'createdAt' },
  { title: '操作', key: 'actions' },
]

const tableData = ref([
  {
    id: '1',
    name: '企业生命体A',
    type: 'CORPORATE',
    status: 'ACTIVE',
    createdAt: '2024-01-01 10:00:00'
  },
  {
    id: '2',
    name: '城市生命体B',
    type: 'URBAN',
    status: 'EVOLVING',
    createdAt: '2024-01-02 11:00:00'
  }
])

// Form 示例数据
const formSubmitting = ref(false)
const formFields = [
  {
    name: 'name',
    label: '生命体名称',
    valueType: 'text',
    rules: [{ required: true, message: '请输入生命体名称' }]
  },
  {
    name: 'type',
    label: '生命体类型',
    valueType: 'select',
    options: [
      { label: '企业生命体', value: 'CORPORATE' },
      { label: '城市生命体', value: 'URBAN' },
      { label: '个体生命体', value: 'INDIVIDUAL' }
    ]
  },
  {
    name: 'description',
    label: '描述',
    valueType: 'textarea'
  }
]

const formInitialValues = {
  name: '',
  type: 'CORPORATE',
  description: ''
}

// Skeleton 示例
const skeletonActive = ref(true)

// Business Components 示例数据
const sampleEntities = ref([
  {
    id: '1',
    name: '智能制造企业',
    type: 'CORPORATE',
    status: 'ACTIVE',
    consciousnessLevel: 'ADVANCED',
    createdAt: '2024-01-01',
    activityLevel: 85,
    influenceScore: 92,
    digitalDNA: {
      traits: ['创新', '效率', '协作', '学习'],
      compatibilityIndex: 88
    },
    relationships: [
      { id: '1', relationType: 'COLLABORATION', targetEntity: { name: '供应商A' } },
      { id: '2', relationType: 'COMPETITION', targetEntity: { name: '竞争对手B' } }
    ]
  }
])

const networkHealth = reactive({ overall: 'healthy' as const })
const networkStats = reactive({
  activeNodes: 156,
  connections: 342,
  messageRate: 1250
})
const networkMetrics = reactive({
  latency: 45,
  bandwidth: 68,
  errorRate: 0.8,
  loadBalance: 85
})
const networkAlerts = ref([
  {
    id: '1',
    level: 'warning' as const,
    message: '网络延迟较高',
    description: '当前网络延迟为 45ms，建议检查网络连接',
    timestamp: '2024-01-01 10:00:00'
  }
])

// 事件处理方法
const handleTableRefresh = () => {
  tableLoading.value = true
  setTimeout(() => {
    tableLoading.value = false
    announce('表格数据已刷新')
  }, 1000)
}

const handleTableSearch = (value: string) => {
  console.log('搜索:', value)
  announce(`正在搜索: ${value}`)
}

const handleAddEntity = () => {
  console.log('新增生命体')
  announce('打开新增生命体表单')
}

const handleView = (record: any) => {
  console.log('查看:', record)
  announce(`查看生命体: ${record.name}`)
}

const handleEdit = (record: any) => {
  console.log('编辑:', record)
  announce(`编辑生命体: ${record.name}`)
}

const handleFormSubmit = async (values: any) => {
  formSubmitting.value = true
  console.log('表单提交:', values)
  
  // 模拟提交
  setTimeout(() => {
    formSubmitting.value = false
    announce('表单提交成功')
  }, 2000)
}

const handleFormReset = () => {
  console.log('表单重置')
  announce('表单已重置')
}

const handleCardRefresh = () => {
  console.log('卡片刷新')
  announce('统计数据已刷新')
}

const handleEntityView = (entity: any) => {
  console.log('查看生命体:', entity)
  announce(`查看生命体详情: ${entity.name}`)
}

const handleEntityEdit = (entity: any) => {
  console.log('编辑生命体:', entity)
  announce(`编辑生命体: ${entity.name}`)
}

const handleEntityDelete = (entity: any) => {
  console.log('删除生命体:', entity)
  announce(`删除生命体: ${entity.name}`)
}

const handleNetworkRefresh = () => {
  console.log('网络状态刷新')
  announce('网络状态已刷新')
}

// 全局加载示例
const showGlobalLoading = () => {
  showLoading({
    tip: '正在加载数据...',
    description: '请稍候，系统正在处理您的请求'
  })
  
  setTimeout(() => {
    hideLoading()
    announce('数据加载完成')
  }, 3000)
}

const showProgressLoading = () => {
  showLoading({
    tip: '正在处理...',
    showProgress: true,
    progress: 0
  })
  
  let progress = 0
  const timer = setInterval(() => {
    progress += 10
    setProgress(progress)
    
    if (progress >= 100) {
      clearInterval(timer)
      setTimeout(() => {
        hideLoading()
        announce('处理完成')
      }, 500)
    }
  }, 200)
}

const hideGlobalLoading = () => {
  hideLoading()
}

// 无障碍功能测试
const updateAccessibilityConfig = () => {
  updateConfig(accessibilityConfig.value)
  announce('无障碍设置已更新')
}

const testScreenReader = () => {
  announce('这是一个屏幕阅读器测试消息', 'assertive')
}

const testKeyboardNavigation = () => {
  announce('请使用 Tab 键进行导航，使用方向键在菜单中移动')
}

// 工具方法
const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    ACTIVE: 'green',
    INACTIVE: 'orange',
    EVOLVING: 'blue',
    ARCHIVED: 'gray'
  }
  return colorMap[status] || 'default'
}

const getStatusLabel = (status: string) => {
  const labelMap: Record<string, string> = {
    ACTIVE: '活跃',
    INACTIVE: '休眠',
    EVOLVING: '进化中',
    ARCHIVED: '已归档'
  }
  return labelMap[status] || status
}
</script>

<style scoped>
.component-examples {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
}

.example-section {
  margin-bottom: 48px;
}

.example-item {
  margin-bottom: 32px;
  padding: 24px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  background: #fff;
}

.example-item:last-child {
  margin-bottom: 0;
}

/* 暗黑模式适配 */
[data-theme="dark"] .example-item {
  background: rgba(255, 255, 255, 0.04);
  border-color: #303030;
}
</style>